<template>
  <div class="app-container">
    <div class="filter-container">
      <el-cascader
        v-model="searchCityChoose"
        class="filter-item"
        :options="cityTree"
        @change="handleSearchCityChange"
      />
      <el-select v-model="searchData.type_sub_id" class="filter-item" placeholder="请选择类型">
        <el-option
          v-for="item in typeTree"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="景点名称" align="center" width="350px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleOpenMap(row)">{{ row.en_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" width="80px">
        <template slot-scope="{row}">
          <span>{{ row.type_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="80px">
        <template slot-scope="{row}">
          <span>{{ row.type_sub_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="省" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.province_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="市" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.city_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="费用" width="80px" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.fee_ticket_has === 1" type="success">免费</el-tag>
          <el-tag v-if="row.fee_ticket_has === 2" type="danger">收费</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开放时间" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.open_time }} - {{ row.close_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="热门" width="60px" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.is_hot === 0" type="danger">否</el-tag>
          <el-tag v-if="row.is_hot === 1" type="success">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="推荐" width="60px" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.is_recommend === 0" type="danger">否</el-tag>
          <el-tag v-if="row.is_recommend === 1" type="success">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="80px">
        <template slot-scope="{row}">
          <el-tag v-if="row.status === 1" type="info">待审核</el-tag>
          <el-tag v-if="row.status === 2" type="success">已审核</el-tag>
          <el-tag v-if="row.status === 99" type="danger">已删除</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <router-link class="el-button el-button--success el-button--mini" :to="'image/list/' + row.id">图片<i class="el-icon-upload el-icon--right" /></router-link>
          <el-button size="mini" type="danger" @click="handleReviewOpen(row)">
            审核
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="searchData.pageIndex" :limit.sync="searchData.pageSize" @pagination="getList" />

    <!-- 弹窗  -->
    <el-dialog title="创建/编辑景点" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="addData" label-position="left" label-width="90px" style="width: 800px; margin-left:50px;">
        <el-tabs type="card">
          <el-tab-pane label="基本数据">
            <el-form-item label="中文名称" prop="cn_name">
              <el-input v-model="addData.cn_name" />
            </el-form-item>
            <el-form-item label="英文名称" prop="en_name">
              <el-input v-model="addData.en_name" />
            </el-form-item>
            <el-form-item label="开放时间" prop="open Time">
              <el-time-picker
                v-model="tmpOpenTimeRange"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
              />
            </el-form-item>
            <el-form-item label="门票" prop="fee_ticket_has">
              <el-radio v-model="addData.fee_ticket_has" label="1" border>免费</el-radio>
              <el-radio v-model="addData.fee_ticket_has" label="2" border>收费</el-radio>
            </el-form-item>

            <el-form-item label="门票费用" prop="fee_ticket_amount">
              <el-input v-model="addData.fee_ticket_amount" size="2" placeholder="门票费用" />
            </el-form-item>

            <el-form-item label="内置收费" prop="fee_inner_project_has">
              <el-radio v-model="addData.fee_inner_project_has" label="1" border>免费</el-radio>
              <el-radio v-model="addData.fee_inner_project_has" label="2" border>收费</el-radio>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="空间数据">
            <el-form-item label="省/市" prop="province">
              <el-cascader
                v-model="tmpCityChoose"
                :options="cityTree"
                @change="handleCityChange"
              />
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="addData.address" />
            </el-form-item>

            <el-form-item label="经度" prop="x">
              <el-input v-model="addData.x" maxlength="20" placeholder="经度" />
            </el-form-item>
            <el-form-item label="维度" prop="y">
              <el-input v-model="addData.y" maxlength="20" placeholder="维度" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="内容">
            <tinymce id="tinymce" v-model="addData.content" />
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>

    <el-drawer
      :visible.sync="reviewDrawerStatus"
      direction="rtl"
      custom-class="demo-drawer"
      :before-close="handleReviewClose"
    >
      <div class="review-drawer-box app-container">
        <el-form ref="dataForm" :rules="rules" label-position="left" label-width="90px">
          <el-form-item label="审核结果" prop="status">
            <el-radio v-model="reviewData.status" label="1" border>通过</el-radio>
            <el-radio v-model="reviewData.status" label="2" border>不通过</el-radio>
          </el-form-item>
          <div style="padding-left:250px">
            <el-button type="primary" @click="handleReviewSubmit()">
              提交审核
            </el-button>
          </div>
        </el-form>
      </div>

    </el-drawer>
    <el-dialog :visible.sync="dialogMapVisible" title="详细地图">
      <img
        width="1200px"
        height="450px"
        src="https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=9jLmrPRtvcaj7L86faKhqA7CqxI="
      >
    </el-dialog>
  </div>
</template>

<script>
import { elementList, elementAdd, elementDel } from '@/api/element'
import Tinymce from '@/components/Tinymce'

import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import router from '../../router' // secondary package based on el-pagination

export default {
  name: 'AdList',
  components: { Pagination, Tinymce },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '待审核',
        '1': '已审核',
        '2': '已上架',
        '99': '已删除'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      reviewDrawerStatus: false,
      reviewData: {
        status: '1'
      },
      imageCoverList: [],
      imageViewList: [],
      currentItemId: 0,
      imageUploadUrl: process.env.VUE_APP_BASE_API + 'tourist/uploadImage',
      imageFileList: [],
      tmpOpenTimeRange: [],

      // 城市
      tmpCityChoose: [],
      cityTree: [],
      searchCityChoose: {},

      // 类型
      typeTree: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      searchData: {
        pageIndex: 1,
        pageSize: 20,
        provinceId: 'all',
        cityId: 'all',
        type_sub_id: 'all',
        status: 'all'
      },

      statusOptions: {
        '0': '',
        '1': '',
        '2': ''
      },
      addData: {
        id: 0,
        cn_name: '',
        en_name: '',
        province_id: 0,
        city_id: 0,
        address: '',
        content: '',
        type_id: 1,
        open_time: '08:00',
        close_time: '22:00',
        open_week_day: [],
        x: 0,
        y: 0,
        fee_ticket_has: '1',
        fee_inner_project_has: '1',
        fee_ticket_amount: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogUploadVisible: false,
      dialogUploadStatus: '',

      dialogMapVisible: false,
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        cn_name: [{ required: true, message: '需要填写中文名称', trigger: 'blur' }],
        en_name: [{ required: true, message: '需要填写英文名称', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      elementList(this.searchData).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.cityTree = response.data.cityList
        this.typeTree = response.data.typeList
        console.log(this.cityTree)

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.searchData.pageIndex = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    resetAddData() {
      this.addData = {
        id: 0,
        cn_name: '',
        en_name: '',
        province_id: 0,
        city_id: 0,
        address: '',
        type_id: 1,
        open_time: '08:00',
        close_time: '22:00',
        open_week_day: [],
        x: 0,
        y: 0,
        fee_ticket_has: '1',
        fee_inner_project_has: '1',
        fee_ticket_amount: 0
      }
    },
    handleCreate() {
      this.resetAddData()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          elementAdd(this.addData).then((response) => {
            console.log(response)
            this.list.unshift(this.addData)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleOpenMap(row) {
      this.dialogMapVisible = true
    },
    handleRedirectToImage(id) {
      router.push({ path: 'image/list', query: { id: id }})
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除 ' + row.cn_name + ' ?')
        .then(_ => {
          elementDel(row.id).then((response) => {
            this.$notify({
              title: '处理成功',
              message: '删除 ' + row.cn_name + ' 成功!',
              type: 'success',
              duration: 2000
            })
          })
        })
        .catch(_ => {
        })
    },
    handleReviewOpen(row) {
      this.reviewDrawerStatus = true
    },
    handleReviewSubmit() {
      this.reviewDrawerStatus = true
    },
    handleReviewClose() {
      this.reviewDrawerStatus = false
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 选择省份和城市触发
    handleCityChange(value) {
      const provinceId = value[0]
      const cityId = value[1]
      this.addData.province_id = provinceId
      this.addData.city_id = cityId
    },
    // 选择省份和城市触发
    handleSearchCityChange(value) {
      const provinceId = value[0]
      const cityId = value[1]
      this.searchData.provinceId = provinceId
      this.searchData.cityId = cityId
    }
  }
}
</script>
